package com.neusoft.shopping.manager.service;

import com.neusoft.shopping.manager.dao.PictureDAOImpl;
import com.neusoft.shopping.manager.entity.PictureEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class PictureService {
    @Autowired
    private PictureDAOImpl dao;

    public List<PictureEntity> qureyAll(){
        return dao.qureyAll();
    }

    public PictureEntity qureyBysGoodsno(Integer goodsno){
        return dao.qureyByGoodsno(goodsno);
    }

    public PictureEntity qureyFirst(Integer goodsno){
        return dao.qureyFirst(goodsno);
    }

    public int add_picture(PictureEntity picture){
        return dao.add_picture(picture);
    }

    public int dofile(MultipartFile multipartFile ,Integer goodsno){
        if(!multipartFile.getOriginalFilename().equals("")){
            String sfname = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String newName = UUID.randomUUID().toString().replace("-","X");
            File newfile = new File("/D/images/picture/"+newName+goodsno+sfname);
            try {
                multipartFile.transferTo(newfile);
                PictureEntity picture=new PictureEntity();
                picture.setGoodsno(goodsno);
                picture.setUrl("http://47.93.56.220:9000/picture/"+newName+goodsno+sfname);
                picture.setIsfirst("Y");
                this.add_picture(picture);
                return 1;
            } catch (IOException e) {
                return 0;
            }
        }
        return 0;
    }

    public int update_stockByPictureno(PictureEntity picture){
        return dao.update_stockByPictureno(picture);
    }
    public int del_picture(Integer pictureno){
        return dao.del_picture(pictureno);
    }
}
